package com.itheima.utils;
;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

public class HttpGetUtils {
    public static String getUId(String name)  {
        String url = "https://map.baidu.com/";
        String param = "su?wd=" + name + "&cid=127&type=0&pc_ver=2";
        String result = null;
        try {
            result = get(url + param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int lastIndex = result.indexOf("$");   //获取第一次
        int frontIndex=0;
        for (int i = 0; i <= 4; i++) {      //循环取出索引
            lastIndex = result.indexOf("$", (lastIndex) + 1);
            if (i == 3) {
                frontIndex = lastIndex;
            }
        }
        String uid = result.substring(frontIndex+1, lastIndex);
        return uid;
    }

    // HttpGet方式
    public static String get(String url) throws Exception {
        String content = null;
        URLConnection urlConnection = new URL(url).openConnection();
        HttpURLConnection connection = (HttpURLConnection) urlConnection;
        connection.setRequestMethod("GET");
        //连接
        connection.connect();
        //得到响应码
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader
                    (connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder bs = new StringBuilder();
            String l;
            while ((l = bufferedReader.readLine()) != null) {
                bs.append(l).append("\n");
            }
            content = bs.toString();
        }
        return content;
    }
}


